import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ride_rex/constant.dart';
import 'package:ride_rex/generated/assets.dart';
import 'package:ride_rex/main/mine/edit_info/edit_info_logic.dart';
import 'package:ride_rex/service/user_service.dart';
import 'package:ride_rex/standard/app_colors.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class EditInfoPage extends GetView<EditInfoLogic> {
  const EditInfoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      titleStr: ' ',
      scaffoldBackgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      child: GetBuilder<EditInfoLogic>(
        init: EditInfoLogic(),
        assignId: true,
        builder: (logic) {
          return ValueListenableBuilder(
            valueListenable: UserService.instance.notifierOfMineInfo,
            builder: (BuildContext context, value, Widget? child) {
              return Column(
                children: [
                  _buildAvatar().paddingTop(68.w),
                  _buildItem('Nick Name', _buildNameInput()).paddingTop(32.w),
                  _buildItem('Date of Birth', _buildChooseBirth()).paddingTop(24.w),
                  _buildItem('Country', _buildChooseCountry()).paddingTop(24.w),
                  const Spacer(),
                  Padding(
                    padding: EdgeInsets.only(left: 24.w, right: 24.w, bottom: 84.w).safeBottom(),
                    child: _buildSubmit(),
                  ),
                ],
              );
            },
          );
        },
      ),
    );
  }

  Widget _buildNameInput() {
    return TextField(
      controller: controller.textEditingController,
      style: const TextStyle(fontSize: 16, color: AppColors.text),
      textAlign: TextAlign.right,
      decoration: InputDecoration(
        hintText: '',
        hintStyle: const TextStyle(fontSize: 16, color: AppColors.text3),
        contentPadding: EdgeInsets.symmetric(vertical: 14.w),
        border: InputBorder.none,
        isCollapsed: true,
        enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
        focusedBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
      ),
      inputFormatters: [LengthLimitingTextInputFormatter(InputLimit.nameLimit)],
    );
  }

  Widget _buildChooseBirth() {
    return ButtonWidget.text(
      controller.birth,
      textColor: AppColors.text,
      fontSize: 16,
      alignment: Alignment.centerRight,
      height: 44.w,
      hasInkWell: false,
      onTap: () {
        ActionBottomSheet.showDatePicker(
          onConfirm: (DateTime? dateTime, String year, String month, String day) {
            if (dateTime == null) return;
            int age = DateTime.now().year - dateTime.year;
            if (age < 18) {
              Loading.toast('You must be at least 18 years old');
              return;
            }
            controller.birth = '$year-${toDouble(month)}-${toDouble(day)}';
            controller.update();
          },
        );
      },
    );
  }

  String toDouble(String value) {
    if (value.length == 1) {
      return '0$value';
    }
    return value;
  }

  Widget _buildChooseCountry() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        ButtonWidget.text(
          controller.country,
          textColor: AppColors.text,
          fontSize: 16,
          alignment: Alignment.centerRight,
          height: 44.w,
          hasInkWell: false,
          onTap: () {
            if (controller.countryList.isEmpty) return;
            ActionBottomSheet.showDataPicker(
              data: controller.countryList,
              onConfirm: (String value) {
                controller.country = value;
                controller.update();
              },
            );
          },
        ),
        Icon(Icons.arrow_forward_ios_rounded, size: 14.w, color: Colors.black.withOpacity(0.5)),
      ],
    );
  }

  Widget _buildAvatar() {
    bool hasAvatar = controller.filePath.isNotEmpty;
    return ButtonWidget(
      onTap: controller.changeAvatar,
      hasInkWell: false,
      child: Stack(
        children: [
          hasAvatar
              ? ImageWidget.file(
                  controller.filePath,
                  width: 98.w,
                  height: 98.w,
                  radius: 98.w,
                  fit: BoxFit.cover,
                )
              : ImageWidget.url(
                  UserService.instance.notifierOfMineInfo.value.avatarThumbUrl ?? '',
                  width: 98.w,
                  height: 98.w,
                  radius: 98.w,
                  fit: BoxFit.cover,
                ),
          IconWidget.image(Assets.pngMyTakePhoto, size: 26.w).positioned(bottom: 0, right: 12.w),
        ],
      ),
    );
  }

  Widget _buildSubmit() {
    return ButtonWidget.text(
      'Submit',
      textColor: Colors.white,
      fontWeight: FontWeight.bold,
      gradient: AppColors.primaryGradient,
      height: 48.w,
      borderRadius: 48.w,
      alignment: Alignment.center,
      onTap: controller.submit,
    );
  }

  Widget _buildItem(String title, Widget right) {
    return ButtonWidget(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      height: 44.w,
      backgroundColor: '#F6F8FA'.toColor,
      borderRadius: 8.w,
      child: Row(
        children: [
          TextWidget.oneLine(text: title, fontSize: 12, color: Colors.black.withOpacity(0.3)),
          right.alignRight().expanded(),
        ],
      ),
    ).paddingHorizontal(32.w);
  }
}
